// 在指定dom内绑定所有loading-btn
function bindLoadingBtn(elem) {
  layui.use(function () {
    var $ = layui.jquery;
    elem.find('.loading-btn').off('click').on('click', function () {
      var target = event.currentTarget;
      $(target).addClass('disabled');
      $(target).append('<i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"></i>');
      var resetTime = $(target).attr("data-reset-time");
      if (!resetTime) {
        // 默认禁用 1 秒
        resetTime = 1000;
      }
      if (resetTime !== "0") {
        setTimeout(function () {
          $(target).removeClass("disabled").find(".layui-icon-loading-1").remove();
        }, resetTime);
      }
    })
  })
}

function layMsg(msg, offset) {
  layui.use('layer', function () {
    let layer = layui.layer;
    if (!offset) {
      layer.msg(msg, {
        offset: '100px'
      });
    } else {
      layer.msg(msg, {
        offset: offset
      });
    }
  })
}

function formAjax(url, method, formId, successCallback, errorCallback) {
  layui.use(function () {
    let $ = layui.jquery;
    formDataAjax(url, method, new FormData($(formId)[0]), successCallback, errorCallback);
  })
}

function formDataAjax(url, method, formData, successCallback, errorCallback) {
  layui.use('layer', function () {
    let $ = layui.jquery;
    $.ajax({
      url: url,
      type: method,
      data: formData,
      contentType: false,
      processData: false,
      success: function (result) {
        if (typeof successCallback === 'function') {
          successCallback(result);
        } else {
          layMsg(result);
        }
      },
      error: function () {
        if (typeof errorCallback === 'function') {
          errorCallback();
        } else {
          layMsg("服务器开小差啦。。。");
        }
      }
    });
  })
}